package cn.woniu.wxy.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * @author NCQ
 * @date 2023/1/7
 */
@Configuration
public class WebCommonConfig implements WebMvcConfigurer {

    /**
     * 跨域配置
     *
     * @param registry
     */
    @Value("${imgPath.path}")
    private String goodImgPath;
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        WebMvcConfigurer.super.addCorsMappings(registry);
//        registry.addMapping("/**") // 访问所有东西都跨域
//                .allowedOriginPatterns("*")
//                .allowedOrigins("Http://localhost:8080","null")
//                //.allowedHeaders("*")
//                .allowedMethods("POST","GET","PUT","OPTIONS","DELETE") //
//                .maxAge(3600) // 最大响应时间
//                .allowCredentials(true); // 是否携带信息
//    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File dir = new File(goodImgPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String dirPath = dir.getAbsolutePath();
        registry.addResourceHandler("/file/**").addResourceLocations("file:" + dirPath+File.separator);
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个数据大小
        factory.setMaxFileSize(DataSize.parse("10MB")); // KB,MB
        // 总上传数据大小
        factory.setMaxRequestSize(DataSize.parse("100MB"));
        return factory.createMultipartConfig();
    }

}
